<?php
/**
 * BasicRenderer class definition
 *   
 * @author Sean Crystal <seancrystal@gmail.com>
 * @package MutantVole
 */
require_once 'interfaces/iViewRenderer.php';
require_once 'lib/HTML_QuickForm/QuickForm/Renderer/Object.php';

/**
 * Renders Views using plain PHP
 * @package MutantVole
 * @subpackage Renderers
 */ 
class BasicRenderer extends ViewRenderer implements iViewRenderer {
	/**
     * Templates are just PHP files
	 */ 	
	const TEMPLATE_EXT = '.php';
	
	/**
     * Renders the views
	 */ 	
	public function Render() {
		$this->CoalesceViews();
		$this->FlattenProperties();
		
		if (empty($this->templateFile) && !($this->SetTemplateFile(TEMPLATE_PREFIX . self::TEMPLATE_EXT))) {
			throw new RendererTemplateFileNotFoundException(TEMPLATE_PREFIX . self::TEMPLATE_EXT);
		}
		
		include $this->templateFile;		
	}
	
	/**
     * Flattens all properties onto the object for direct access in the
	 * template. Does the same with HTML_QuickForms, creating a member with the
	 * View's formName 
	 */ 
	protected function FlattenProperties() {
		if (count($this->properties) > 0) {
			foreach ($this->properties as $key => $value) {
				$this->$key = $value;
			}
		}
		
		if (count($this->views) > 0) {
			foreach ($this->views as $view) {
				if ($view instanceof HTMLQuickFormView) {
					$renderer = new HTML_QuickForm_Renderer_Object(false);				
					$view->form->accept($renderer);	
					$name = $view->formName;
					
					$this->$name->attributes = $renderer->toObject()->attributes;
					$this->$name->errors     = $renderer->toObject()->errors;
					
					foreach ($renderer->toObject()->elements as $element) {
						$this->$name->{$element->name} = $element;
					}										
				} 
			}
		}
	}
}

